<style scoped>
  .app-container >>> .scode {
    cursor: pointer;
    color: #20B2AA;
    text-decoration: underline;
  }
  .app-container >>> .scodeth {
    color: #515a6e;
  }
</style>
<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="主键" prop="guid">
        <el-input
          v-model="queryParams.search"
          placeholder="客户/货运单编号/车牌号/地块名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付状态">
          <el-select v-model="queryParams.payStatusList" multiple placeholder="请选择支付状态" size="small">
            <el-option
              v-for="dict in payStatusOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="statusList">
        <el-select v-model="queryParams.statusList" clearable filterable placeholder="请选择状态" size="small" multiple>
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="parseInt(dict.dictValue)"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采收主体" prop="orgId">
        <el-select v-model="queryParams.orgId" filterable clearable placeholder="请选择采收主体" clearable size="small">
          <el-option
            v-for="dict in orgs"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
            @click.native="getStore($event, dict)"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="库房" prop="storeroomeIdList">
        <el-select v-model="queryParams.storeroomeIdList" clearable filterable placeholder="请选择库房" size="small" multiple>
          <el-option
              v-for="item in roomOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门" prop="departidList">
        <el-select v-model="queryParams.departidList" clearable filterable placeholder="请选择部门" size="small" multiple>
          <el-option
              v-for="item in departOptions"
              :key="item.guid"
              :label="item.name"
              :value="item.guid"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="供应商" prop="orgId">
        <el-select v-model="queryParams.supplierId" filterable clearable placeholder="请选择供应商" size="small">
          <el-option
            v-for="item in suppliers"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="合同" prop="contractid">
        <el-select v-model="queryParams.contractid" clearable filterable placeholder="请选择合同" size="small" >
          <el-option
              v-for="item in contractOptions"
              :key="item.guid"
              :label="item.name+'['+item.code+']'"
              :value="item.guid"
            ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="startdate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.startdate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期">
            </el-date-picker>
            <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.enddate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期">
            </el-date-picker>
      </el-form-item>
      <el-form-item label="入库时间" prop="startdate">
        <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.insrstartdate" type="date" value-format="yyyy-MM-dd" placeholder="选择开始日期">
            </el-date-picker>
            <el-date-picker clearable size="small" style="width: 200px" v-model="queryParams.insrenddate" type="date" value-format="yyyy-MM-dd" placeholder="选择结束日期">
            </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['harvest:freightorder:export']"
        >导出</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          icon="el-icon-printer"-->
<!--          size="mini"-->
<!--          :disabled="ids.length != 1"-->
<!--          @click="handleWhinformExport"-->
<!--        >打印入库单</el-button>-->
<!--      </el-col>-->
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="freightorderList" @selection-change="handleSelectionChange" :show-summary="true" :summary-method="sumIt" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center" prop="code" label-class-name="scodeth" class-name="scode" width="100">
        <template slot-scope="scope">
          <span @click="viewIt(scope.row.id)">{{ scope.row.code }}</span>
          <!--            <span>{{ scope.row.sellcode }}</span>-->
        </template>
      </el-table-column>
      <el-table-column label="采收主体" align="center" prop="orgName" />
      <el-table-column label="采收类型" align="center" prop="typeName" />
      <el-table-column label="入库库房" align="center" prop="storeroom" />
      <el-table-column label="供应商" align="center" prop="supplierName" />
      <el-table-column label="品种" align="center" prop="variety" />
      <el-table-column label="规格" align="center" prop="specification" />
      <el-table-column label="结算重量" align="center" prop="weight" width="100" />
      <el-table-column label="过磅重量" align="center" prop="hweight" />
      <el-table-column label="入库重量" align="center" prop="netWeight" width="100" />
      <el-table-column label="结算单价" align="center" prop="actualSettl" />
      <el-table-column label="结算金额" align="center" prop="settlement" width="100" />
      <el-table-column label="状态" align="center" prop="statusName" />
      <el-table-column label="付款方式" align="center" prop="paytype" />
      <el-table-column label="支付状态" align="center" prop="paystatusName" />
      <el-table-column label="部门" align="center" prop="department" />
      <el-table-column label="采收负责人" align="center" prop="operator" />
      <el-table-column label="采收日期" align="center" prop="createtime" />
      <el-table-column label="承运人" align="center" prop="carcode" width="180">
        <template slot-scope="scope">
          <span>{{ scope.row.drivername}}--{{ scope.row.driverphone}}--{{ scope.row.carcode}}</span>
        </template>
      </el-table-column>
      <!-- <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"

            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['harvest:freightorder:edit']"
          >修改</el-button>
        </template>
      </el-table-column> -->
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改货运单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFreightorder, getFreightorder, delFreightorder, addFreightorder, updateFreightorder, exportFreightorder, exportWhinformExport } from "@/api/harvest/freightorder";
import { findStoreroom,getDepartmentList,findStoreroomListByPermiss } from "@/api/public";
import { getContracts } from "@/api/harvest/procurementcontract";
import { findSupploerlist, findOrganizationList } from "@/api/public";

export default {
  name: "Freightorder",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 货运单表格数据
      freightorderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        functionType: 26,
        pageNum: 1,
        pageSize: 10,
        paystatus: null,
        status: null,
        storeroomcode: null,
        startdate: null,
        enddate: null,
        insrenddate: null,
        contractid: '',
        departid: null,
        payStatusList: null,
        statusList: [],
        storeroomeIdList: [],
        departidList: [],
        orgId: '',
        supplierId: ''
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      roomOptions: [],
      departOptions: [],
      contractOptions: [],
      statusOptions: [],
      payStatusOptions: [],
      suppliers: [],
      orgs: [],
      totalNum: '',
      totalWeight: '',
      totalHweight: '',
      totalSettlement: '',
      printUrl: 'http://testadmin.tudouji.com.cn:8095/RDP-SERVER/rdppage/main/a3138b35bca80f8844b950bfd7f3e480?focode='
    };
  },
  created() {
    this.queryParams.startdate = this.getMonthFirDate();
    this.getList();
    // this.findStoreroom();
    this.getDepartmentList();
    this.getContractsList();
    this.getDicts("freightorder_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("freightorder_paystatus").then(response => {
      this.payStatusOptions = response.data;
    });
    //查询组织
    findOrganizationList().then(response => {
      this.orgs = response.data;
    });
    //查询供应商
    findSupploerlist({}).then(response => {
      this.suppliers = response.data;
    });
  },
  methods: {
    getStore(event, item){
      findStoreroomListByPermiss({orgguid: item.guid,functionType: 10}).then(response => {
        this.roomOptions = response.data;
      });
    },
    sumIt(param) {
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        // index 第几列从0开始
        if (index === 1) {
          sums[1] = `合计(${this.totalNum}条)`;
          return;
        }
        if (index === 8) {
          sums[index] = this.totalWeight;
          return;
        }
        if (index === 10) {
          sums[index] = this.totalHweight;
          return;
        }
        if (index === 12) {
          sums[index] = this.totalSettlement;
          return;
        }
        sums[index] = '-';
      });
      return sums;
    },
    viewIt(id) {
      this.$router.push({path: '/harvest/forderinfo', query: {id: id}});
    },
    getDepartmentList(){
      getDepartmentList().then(response => {
        this.departOptions = response.data;
      });
    },
    getContractsList(){
      getContracts().then(response => {
        this.contractOptions = response.data;
      });
    },
    findStoreroom(){
       findStoreroom().then(response => {
        this.roomOptions = response.data;
      });
    },
    /** 查询货运单列表 */
    getList() {
      console.log(this.queryParams)
      this.loading = true;
      listFreightorder(this.queryParams).then(response => {
        this.freightorderList = response.rows;
        this.total = response.total;
        const totals = response.sumObj;
        if (!totals) return;
        this.totalNum = totals.num;
        this.totalWeight = totals.weight;
        this.totalHweight = totals.hweight;
        this.totalSettlement = totals.settlement;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        autoid: null,
        guid: null,
        ordercode: null,
        code: null,
        batchcode: null,
        batchid: null,
        plantorid: null,
        plantor: null,
        plantorphone: null,
        drivername: null,
        driverphone: null,
        provence: null,
        city: null,
        country: null,
        street: null,
        carcode: null,
        amount: null,
        arealandid: null,
        arealand: null,
        variety: null,
        productinfoid: null,
        weight: null,
        price: null,
        settlement: null,
        harvest: null,
        storeroomcode: null,
        storeroom: null,
        storehousecode: null,
        storehouse: null,
        createtime: null,
        status: 0,
        operatorid: null,
        lastupdate: null,
        remark: null,
        unloadtime: null,
        qatype: null,
        specification: null,
        specificationid: null,
        spotcheckrate: null,
        discountrate: null,
        soilchkrate: null,
        unqualifiedchkrate: null,
        deducttype: null,
        setlwgtype: null,
        contractid: '',
        hweight: null,
        organizationid: null,
        paystatus: 0,
        pkgwght: null,
        rweight: null,
        hrweight: null,
        wghtperpkg: null,
        pkgcount: null,
        unprocdAmount: null,
        isdiscount: null,
        latitude: null,
        longitude: null,
        distance: null,
        spguid: null,
        actualsettl: null,
        departid: null,
        department: null,
        flowid: null,
        strguid: null,
        refuseflag: null,
        operator: null,
        acceptstatus: 0,
        ratend: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.guid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加货运单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const autoid = row.autoid || this.ids
      getFreightorder(autoid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改货运单";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.autoid != null) {
            updateFreightorder(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFreightorder(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const autoids = row.autoid || this.ids;
      this.$confirm('是否确认删除该数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFreightorder(autoids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      let that = this;
      let par = that.queryParams;
      this.$confirm('是否确认导出所有货运单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportFreightorder(par);
        }).then(response => {
          that.download(response.msg);
        })
    },
    /** 导出入库单按钮操作 */
    handleWhinformExport() {
      let that = this;
      const autoid = this.ids[0];
      if (autoid) {
        window.open(that.printUrl + autoid, "_blank", "toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
      }
    },
    myPrint() {
      window.open("", "_blank", "toolbar=no,menubar=no,scrollbars=yes,resizable=yes,location=no,status=no");
      var win =window.opener;
        // win.document.write(`<iframe name='${title}' src='${url}' style="position: absolute;border:0; top:0px; left:0px; bottom:0px; right:0px; width:100%; height:100%;"></iframe>`);
      win.document.title = '你好';
      let subOutputRankPrint = document.createElement("div");
      subOutputRankPrint.innerHTML = 1111111111111;
      subOutputRankPrint.className = 'test';
      win.document.body.append(subOutputRankPrint)
      // window.open("_blank");
      // // 1. 设置要打印的区域 div的className
      // let subOutputRankPrint = document.createElement("div");
      // subOutputRankPrint.innerHTML = 1111111111111;
      // document.body.appendChild(subOutputRankPrint)
      // // 2. 设置页面比例
      // document.getElementsByTagName("body")[0].style.zoom = 0.68;
      // window.print();
      // // 3. 还原：将旧的页面储存起来，当打印完成后返给给页面
      // window.location.reload();
    }
  }
};
</script>
